7  Interactive maps

You can plot a static map using plof(sf), but you can also create interactive maps.

Code
library(sf)
TRIPSgeo = st_read("data/TRIPSgeo.gpkg")
Reading layer `TRIPSgeo' from data source `D:\GIS\EITcourse\data\TRIPSgeo.gpkg' using driver `GPKG'
Simple feature collection with 18 features and 7 fields
Geometry type: MULTIPOLYGON
Dimension:     XY
Bounding box:  xmin: -9.500527 ymin: 38.40907 xmax: -8.490972 ymax: 39.06472
Geodetic CRS:  WGS 84
Code
plot(TRIPSgeo)

Interactive maps are useful to explore the data, as you can zoom in and out, and click on the points to see the data associated with them.

There are several R packages to create interactive maps. For instance, the tmap package, the leaflet package, and the mapview package.

7.1 Mapview

Mapview allows to create quick interactive maps, only by declaring the function mapview().

Code
library(mapview)
mapview(TRIPSgeo)

To color the points by a variable, you can use the zcol argument.

Code
mapview(TRIPSgeo, zcol = "Total")

As you can see, a color palette is automatically assigned to the continuous variable.

Try to use a categorical variable.

Code
mapview(TRIPSgeo, zcol = "Municipality")

Note that you can change the basemap, and click on the geometries to see the data associated with them.

You can go crazy with all the options that mapview offers. Please refer to the documentation to see all the options.

7.1.1 Export

You can export a map as an html file or image.

Code
# install.packages("webshot2") # you will need this

map = mapview(TRIPSgeo, zcol = "Total") # fisrt create a objet with the desited map

mapshot2(map, "data/map.html") # as webpage
mapshot2(map, file = "data/map.png") # as image

This is not the most straightforward solution.

7.2 tmap

The tmap package is another package to create interactive maps.

To create a map, you need to declare a tm_shape() for the dataset you are using and a tm_polygons(). (or lines or other) to declare the representation you want.

Code
# install.packages("tmap")
library(tmap)
tmap_mode("view") # by default tmap_mode is "plot" - a static map

tm_shape(TRIPSgeo) + tm_polygons("Total")

7.2.1 Export

With tmap you can directly export the map as an html file or image, using the Viewer panel.

7.3 Rmarkdown

To include a map on a report, website, paper (any type), you can create an Rmarkdown file.

And include a R code chunk with a map. If the output is html, you will get an interactive map on your document!